package com.clz.appdesign.socket;

import android.content.Context;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.Toast;

import com.clz.appdesign.myapp.R;
import com.clz.appdesign.myapp.utils.L;
import com.xuhao.android.libsocket.sdk.ConnectionInfo;
import com.xuhao.android.libsocket.sdk.OkSocket;
import com.xuhao.android.libsocket.sdk.SocketActionAdapter;
import com.xuhao.android.libsocket.sdk.connection.IConnectionManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.widget.Toast.LENGTH_SHORT;

public class SimpleClientActivity extends AppCompatActivity {

    @BindView(R.id.edit_receive_content)
    EditText mEditReceiveContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_client);
        ButterKnife.bind(this);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
       // socketConnect();
        socketConnect2();
    }

    private void socketConnect2() {
        //连接参数设置(IP,端口号),这也是一个连接的唯一标识,不同连接,该参数中的两个值至少有其一不一样
        ConnectionInfo info = new ConnectionInfo("192.168.5.121",4000);
//调用OkSocket,开启这次连接的通道,拿到通道Manager
        IConnectionManager manager = OkSocket.open(info);
//注册Socket行为监听器,SocketActionAdapter是回调的Simple类,其他回调方法请参阅类文档
        manager.registerReceiver(new SocketActionAdapter(){
            @Override
            public void onSocketConnectionSuccess(Context context, ConnectionInfo info, String action) {
                Toast.makeText(context, "连接成功", LENGTH_SHORT).show();
            }
        });
//调用通道进行连接
        manager.connect();
    }

    private void socketConnect() {
        try {
            Socket socket=new Socket("192.168.5.121",4000);
            //设置超时时间
            socket.setSoTimeout(100000);
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line=bufferedReader.readLine();
            mEditReceiveContent.setText("来自服务器的数据"+line);
        } catch (IOException e) {
            e.printStackTrace();
            L.i("socket2",e.getLocalizedMessage());
        }
    }
}
